package controller

import (
	"gin-epg/internal/app/common/rsp"
	"gin-epg/internal/app/entity"
	"gin-epg/internal/app/param"
	"gin-epg/internal/app/service"
	"github.com/gin-gonic/gin"
)

func GetEpgChannelList(c *gin.Context) {
	obj := param.QueryEpgChannelListParam{}
	c.BindJSON(&obj)
	todoList, err := service.GetEpgChannelList(&obj)
	if err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "请求成功", todoList)
	}
}
func GetEpgChannelPage(c *gin.Context) {
	obj := param.QueryEpgChannelPageParam{}
	c.BindJSON(&obj)
	//如果没有设置分页大写和分页序号，这里要设置
	if obj.Current == 0 {
		obj.Current = 1
	}
	if obj.Size == 0 {
		obj.Size = 10
	}
	todoList, err := service.GetEpgChannelPage(&obj)
	if err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "请求成功", todoList)
	}
}

func GetEpgChannelDetail(c *gin.Context) {
	id := c.Query("id")
	epgChannel, err := service.GetEpgChannelById(id)
	if err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "请求成功", epgChannel)
	}
}

func CreateEpgChannel(c *gin.Context) {
	//定义一个EpgChannel变量
	var epgChannel entity.EpgChannel
	//将调用后端的request请求中的body数据根据json格式解析到EpgChannel结构变量中
	c.BindJSON(&epgChannel)
	//将被转换的epgChannel变量传给service层的CreateEpgChannel方法，进行EpgChannel的新建
	err := service.CreateEpgChannel(&epgChannel)
	//判断是否异常，无异常则返回包含200和更新数据的信息
	if err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "新增成功", epgChannel)
	}
}

func UpdateEpgChannel(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		rsp.Error(c, "无效的id")
	}
	epgChannel, err := service.GetEpgChannelById(id)
	if err != nil {
		rsp.Error(c, err.Error())
		return
	}
	c.BindJSON(&epgChannel)
	if err = service.UpdateEpgChannel(epgChannel); err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "更新成功", epgChannel)
	}
}

func DeleteEpgChannelById(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		rsp.Error(c, "无效的id")
	}
	if err := service.DeleteEpgChannelById(id); err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "删除成功", id)
	}
}

func DeleteEpgChannelByName(c *gin.Context) {
	name := c.DefaultQuery("name", "")
	println("name:", name)
	if err := service.DeleteEpgChannelByName(name); err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "删除成功", name)
	}
}

func GetEpgChannelStd(c *gin.Context) {
	name := c.DefaultQuery("name", "")
	println("name:", name)
	todoList, err := service.GetEpgChannelStd(name)
	if err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "请求成功", todoList)
	}
}

func UploadEpgChannelLogoByName(c *gin.Context) {
	// 取 post form-data 参数 name 和 file
	// 其中 name 为频道名字符串，file 为上传文件
	name := c.PostForm("name")
	file, err := c.FormFile("file")

	if err != nil {
		rsp.Error(c, err.Error())
		return
	}

	if err := service.UploadEpgChannelLogoByName(name, file); err != nil {
		rsp.Error(c, err.Error())
	} else {
		rsp.Success(c, "上传成功", name)
	}
}
